package com.myproject.filmrecommendationsys.controller;


import com.myproject.filmrecommendationsys.domain.User;
import com.myproject.filmrecommendationsys.service.IUserService;
import com.myproject.filmrecommendationsys.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags="系统功能")
@RestController
@RequestMapping("/system")
public class SystemController {
    @Autowired
    private IUserService userService;
    /**
     * 模拟用户 登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public String login( String username, String password) {
        User user = userService.selectUserByUsernameAndPassword( username, password);
        if(user!=null){
            log.info("用户登录成功，生成Token！用户名：{}", user.getUsername());
            // 生成JWT Token
            String token = JwtUtil.createToken(user);
            return "登陆成功，获取到token=" + token; // 返回生成的Token
        }else{
            log.warn("用户名或密码错误,登陆失败");
            return "用户名或密码错误";
        }
    }
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        //判断用户名是否存在
        User dbuser = userService.selectUserByUsernameAndPassword(user.getUsername(),user.getPassword());
        if(dbuser!=null){
            return "用户名已存在！";
        }
        log.info("接收到的用户名：{}", user.getUsername());
        log.info("接收到的密码：{}", user.getPassword());

        boolean isSaved = userService.insertUser(user);
        if(isSaved){
            log.warn("注册成功,用户名为"+user.getUsername()+"的用户");
            return "注册成功";
        }else{
            return "注册失败";
        }
    }
}
